package com.gargi.crimepatrol.main;

import java.util.Vector;

import com.gargi.crimepatrol.network.CrimePatrol;
import com.gargi.crimpatrol.utils.Constant;
import com.sun.lwuit.Display;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.list.DefaultListModel;

public class LiveTvList extends List implements ActionListener {
	
	private View view;
	private LiveTvModel livetvmodel;
	private ImageTextCellRenderer imagetextrenderer;
	
	public LiveTvList(View view) {
		this.view = view;
		
		livetvmodel = new LiveTvModel();
		imagetextrenderer = new ImageTextCellRenderer(this);
		
		this.setModel(livetvmodel);
		setImageTextButtonRenderer();
		this.setActionListener();
	}
		
	public View getLiveCatView() {
		return this.view;
	}
			
	public void setCategory(Vector categoryvector) {
		
		livetvmodel.removeAll();
		
		for(int i = 0; i< categoryvector.size();i++) {
			CrimePatrol crimePatrol = (CrimePatrol)categoryvector.elementAt(i);
			if(livetvmodel != null) {
				livetvmodel.addItem(crimePatrol);
			}
		}
				
		Display.getInstance().callSerially(
				new Runnable() {
					
					public void run() {
							LiveTvList.this.repaint();
					}
				});
	}
	
	public void setImageTextButtonRenderer() {
		if(!(this.getRenderer() instanceof ImageTextCellRenderer)) {
			this.setRenderer(imagetextrenderer);
		}else {
			Constant.log("Image Text Button Rendrer already set");
		}
	}

		
	public void actionPerformed(ActionEvent e) {
		int selectedIndex = ((List)e.getSource()).getSelectedIndex();
		Constant.log("Selected Index = "+selectedIndex);
		
		CrimePatrol selectedModel = (CrimePatrol)this.livetvmodel.getItemAt(selectedIndex);
		Constant.log("Streaming url = "+selectedModel.getStreamingurl());
		
		this.view.playVideoUrl(selectedModel.getStreamingurl().trim());
	}
	
	private void setActionListener() {
		this.addActionListener(this);
	}
	
	public class LiveTvModel extends DefaultListModel {
		
		public void addItem(Object item) {
			super.addItem(item);
		}
	}
}
